<?php
declare (strict_types=1);

namespace app\command;

use app\admin\dao\KeywordsAnalysisDao;
use app\common\model\Keywords;
use app\common\model\Knowledge;
use ShidianUtil\Utils\TimeUtil;
use think\console\Command;
use think\console\Input;
use think\console\Output;

class KeywordsAnalysis extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('ka')
            ->setDescription('the keywords analysis command');
    }

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $output->writeln('关键词统计开始');

        $deadline = TimeUtil::stamp(TimeUtil::DAY);

        Keywords::where('keywords','<>','')
            ->select()
            ->each(function (Keywords $record) use($deadline) {
                $keywords = $record->keywords;

                // 统计关键词, 写入结果

                // 包含该关键词的文章
                $keywordsNum = Knowledge::whereRaw("FIND_IN_SET('$keywords', `keywords`)")->count();

                // 包含该关键词的文章
                $titleNum = Knowledge::whereLike('title', "%$keywords%")->count();

                // 包含该关键词的文章
                $readNum = Knowledge::whereLike('title', "%$keywords%")->sum('readNum');

                $params = [
                    'keywords'=> $keywords,
                    'keywordsNum'=> $keywordsNum,
                    'titleNum'=> $titleNum,
                    'readNum'=> $readNum,
                    'deadline'=> $deadline,
                ];

                $this->getKeywordsAnalysisDao()->insertActive($params);
            });

        $output->writeln('关键词统计结束');
    }

    private function getKeywordsAnalysisDao():KeywordsAnalysisDao{
        return app(KeywordsAnalysisDao::class);
    }
}
